package com.toutou.base.bindhelper

import android.graphics.BitmapFactory
import androidx.camera.view.PreviewView
import androidx.databinding.BindingAdapter
import com.google.zxing.BinaryBitmap
import com.google.zxing.MultiFormatReader
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.common.HybridBinarizer
import com.king.camera.scan.AnalyzeResult
import com.king.camera.scan.BaseCameraScan
import com.king.camera.scan.CameraScan
import com.king.camera.scan.analyze.Analyzer
import com.king.zxing.analyze.MultiFormatAnalyzer
import com.toutou.base.util.ActivitiesManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class PreviewBDAdapter {
    companion object {
        private var hasStartCamera = false

        //        初始化
        /**
         * @param openCamera:是否开启相机, 在赋值true之前，要外部自行判断好相机权限
         * * openCamera: activity销毁之前，要关闭相机，否则会影响下次开启
         * scanResultCallback:扫描结果回调 成功回调中，要注意 此时已经关闭了扫描，如果需要继续，需要重新开启
         */
        @JvmStatic
        @BindingAdapter(
            value = ["flight", "localPicPath", "openCamera", "scanResultCallback"],
            requireAll = false
        )
//        设置闪光灯
        fun setFlight(
            view: PreviewView,
            flight: Boolean?,
            localPicPath: String?,
            openCamera: Boolean?,
            scanResultCallback: OnPreviewScanResultCallback?
        ) {
            if (view.tag == null) {
                ActivitiesManager.topActivity()?.let {
                    view.tag = BaseCameraScan<Any>(it, view).apply {
                        setVibrate(true)//震动
                        setAutoStopAnalyze(true)//扫描成功后，自动停止扫描
                        setAnalyzer(MultiFormatAnalyzer() as Analyzer<Any>)//设置扫描类型
//                    bindFlashlightView()//感应光照，不需要
                        setOnScanResultCallback(object : CameraScan.OnScanResultCallback<Any> {
                            override fun onScanResultCallback(result: AnalyzeResult<Any>) {
                                scanResultCallback?.onScanResultCallback(result.result.toString())
                            }

                            override fun onScanResultFailure() {
//                            扫描过程不需要回调失败
                            }
                        })
                    }
                }
            }


            //设置闪光灯
            (view.tag as BaseCameraScan<*>).enableTorch(flight ?: false)

            if (openCamera == true) {
                if (!hasStartCamera) {
                    hasStartCamera = true

//                    在此之前，注意判断相机权限
                    (view.tag as BaseCameraScan<*>).startCamera()
                }
            } else {
                if (hasStartCamera) {
                    (view.tag as BaseCameraScan<*>).stopCamera()
                    hasStartCamera = false
                }
            }

            // 本地图片扫描
            if (localPicPath != null) {
//                解析耗时，去协程跑子线程
                CoroutineScope(Dispatchers.IO).launch {//协程开启异步执行,子线程执行
                    val bitmap = BitmapFactory.decodeFile(localPicPath) ?: null
                    if (bitmap == null) {
                        scanResultCallback?.onScanResultFailure()
                        return@launch
                    }
                    val width = bitmap.width
                    val height = bitmap.height
                    val pixels = IntArray(width * height)
                    bitmap.getPixels(pixels, 0, width, 0, 0, width, height)

                    try {
                        val result = MultiFormatReader().decode(
                            BinaryBitmap(
                                HybridBinarizer(
                                    RGBLuminanceSource(
                                        width,
                                        height,
                                        pixels
                                    )
                                )
                            )
                        )
//                        切换到主线程
                        withContext(Dispatchers.Main){
                            scanResultCallback?.onScanResultCallback(result.text)
                        }
                    } catch (e: Exception) {
//                        切换到主线程
                        withContext(Dispatchers.Main){
                            scanResultCallback?.onScanResultFailure()
                        }
                    }
                }

            }
        }

        interface OnPreviewScanResultCallback {
            fun onScanResultCallback(result: String)
            fun onScanResultFailure()
        }
    }

}